package com.example.activelifecycletest.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.PerformanceHintManager;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.activelifecycletest.R;

/**
 * 广播合集练习
 * @author zhangding
 * @date 2022年04月22日10:12:59
 */
public class LoginActivity extends  BaseActivity {
    private EditText accountEdit;
    private EditText passwordEdit;
    private Button login;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private CheckBox rememberPwd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        accountEdit = (EditText) findViewById(R.id.account);
        passwordEdit = (EditText) findViewById(R.id.password);
        /**
         * 是否保存密码复选框，判断逻辑isChecked为true表示选中,但想得到上次有没有选中只能之持久化到文件中,
         * 因为复选框不存在持久化属性
         */
        rememberPwd = (CheckBox) findViewById(R.id.remember_pwd);
        login = (Button) findViewById(R.id.login);
        // 密码填充
        boolean rememberFlag = preferences.getBoolean("remember_pwd",false);
        if (rememberFlag){
            String account = preferences.getString("account","");
            String pwd = preferences.getString("pwd","");
            accountEdit.setText(account);
            passwordEdit.setText(pwd);
            rememberPwd.setChecked(true);
        }
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String account = accountEdit.getText().toString();
                String password = passwordEdit.getText().toString();
                if (account.equals("admin") && password.equals("123456")){
                    // 密码保存
                    editor = preferences.edit();
                    if (rememberPwd.isChecked()){
                        editor.putBoolean("remember_pwd",true);
                        editor.putString("account",account);
                        editor.putString("pwd",password);
                    }else {
                        editor.clear();
                    }
                    editor.apply();
                    // 登录成功调转到main活动
                    Intent intent = new Intent(LoginActivity.this, LoginMainActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}